<template>
  <div class="category-list-container">
    <div class="header">
      <h2>课程分类管理</h2>
      <div class="actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索分类..."
          :prefix-icon="Search"
          clearable
          @clear="handleSearch"
          @input="handleSearch"
          class="search-input"
        />
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>添加分类
        </el-button>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="categoryList"
      border
      style="width: 100%"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="分类名称" />
      <el-table-column prop="description" label="描述" show-overflow-tooltip />
      <el-table-column prop="courseNum" label="课程数量" width="100" align="center">
        <template #default="{ row }">
          <el-tag type="info" effect="plain" size="small">
            {{ row.courseNum || 0 }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdTime" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="200">
        <template #default="{ row }">
          <el-button-group>
            <el-button type="primary" @click="handleEdit(row)" :icon="Edit" size="small">
              编辑
            </el-button>
            <el-button type="danger" @click="handleDelete(row)" :icon="Delete" size="small">
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      @update:current-page="currentPage = $event"
      @update:page-size="pageSize = $event"
      class="pagination"
    />

    <!-- 分类表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加分类' : '编辑分类'"
      width="500px"
    >
      <el-form
        ref="categoryFormRef"
        :model="categoryForm"
        :rules="categoryRules"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="categoryForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入分类描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="删除提示"
      width="450px"
    >
      <div v-if="selectedCategory">
        <template v-if="selectedCategory.courseNum > 0">
          <el-alert
            type="warning"
            :closable="false"
            show-icon
          >
            <p><b>警告：该分类下有 {{ selectedCategory.courseNum }} 个关联课程</b></p>
            <p>删除分类将同时删除分类下的所有课程及其相关数据，包括收藏记录、评价和浏览历史。</p>
          </el-alert>
        </template>
        <p class="delete-confirm-text">
          您确定要删除分类 <b>{{ selectedCategory.name }}</b> 吗？此操作不可恢复。
        </p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete" :loading="deleting">
            确定删除
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

// 状态变量
const loading = ref(false)
const submitting = ref(false)
const deleting = ref(false)
const dialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const dialogType = ref('add')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchQuery = ref('')
const categoryList = ref([])
const selectedCategory = ref(null)

// 表单相关
const categoryFormRef = ref(null)
const categoryForm = reactive({
  name: '',
  description: '',
  createdTime: null
})

// 表单验证规则
const categoryRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 50, message: '分类名称长度必须在2到50个字符之间', trigger: 'blur' }
  ],
  description: [
    { max: 500, message: '描述长度不能超过500个字符', trigger: 'blur' }
  ]
}

// 防抖函数
const debounce = (fn, delay) => {
  let timer = null
  return (...args) => {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

// 获取分类列表
const fetchCategories = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      search: searchQuery.value
    }
    await request.get('/category/page', params, {
      showDefaultMsg: false,
      onSuccess: (res) => {
        categoryList.value = res.records||[]
        total.value = res.total||0
      }
    })
  } catch (error) {
    console.error('获取分类列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchCategories()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchCategories()
}

// 处理搜索
const handleSearch = debounce(() => {
  currentPage.value = 1
  fetchCategories()
}, 300)

// 处理添加分类
const handleAdd = () => {
  dialogType.value = 'add'
  Object.assign(categoryForm, {
    name: '',
    description: ''
  })
  dialogVisible.value = true
}

// 处理编辑分类
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(categoryForm, {
    id: row.id,
    name: row.name,
    description: row.description
  })
  dialogVisible.value = true
}

// 处理删除分类
const handleDelete = (row) => {
  selectedCategory.value = row
  deleteDialogVisible.value = true
}

// 确认删除分类
const confirmDelete = async () => {
  if (!selectedCategory.value) return
  
  deleting.value = true
  try {
    await request.delete(`/category/${selectedCategory.value.id}`, {
      successMsg: '删除成功'
    })
    deleteDialogVisible.value = false
    fetchCategories()
  } catch (error) {
    console.error('删除分类失败:', error)
  } finally {
    deleting.value = false
  }
}

// 处理表单提交
const handleSubmit = () => {
  categoryFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        if (dialogType.value === 'add') {
          await request.post('/category', categoryForm, {
            successMsg: '添加成功'
          })
        } else {
          const { createdTime, ...updateData } = categoryForm
          await request.put(`/category/${updateData.id}`, updateData, {
            successMsg: '更新成功'
          })
        }
        dialogVisible.value = false
        fetchCategories()
      } catch (error) {
        console.error('保存分类失败:', error)
      } finally {
        submitting.value = false
      }
    }
  })
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '暂无'
  return new Date(date).toLocaleString()
}

// 初始化
onMounted(() => {
  fetchCategories()
})
</script>

<style lang="scss" scoped>
.category-list-container {
  padding: 20px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 24px;
      color: var(--el-text-color-primary);
    }

    .actions {
      display: flex;
      gap: 10px;

      .search-input {
        width: 200px;
      }
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.delete-confirm-text {
  margin-top: 15px;
  font-size: 16px;
}
</style> 